#!/usr/bin/env python3
"""A local page for judging one call's cards: for each card, what was being said, the card, and why the agent wrote
it (its thinking, the research it ran, its one-line decision), with a rating and a reason per card.

  sidekick-eval [--call <id or prefix>] [--port 8765] [--no-open] [--env staging]

Defaults to the newest call. Ratings go to calls/<call>/eval.jsonl (one JSON line per rating, the last one per card
wins), which sidekick-tune and the agent's tuning read. Nothing leaves this machine: the page is served on localhost
from the call's own files.
"""
import argparse
import json
import os
import re
import shlex
import sys
import time
import webbrowser
from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

sys.dont_write_bytecode = True
sys.path.insert(0, str(Path(__file__).resolve().parent))
import sidekick_context as ctx  # noqa: E402

SPEECH = re.compile(r"^\[(\d{4}-\d\d-\d\dT[^\]]+)\]\s+([A-Z][\w'-]*(?: [A-Z][\w'-]*)+):(.*)$")
EVENT = re.compile(r"<event>(.*?)</event>", re.S)
UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")


def stamp(v):
    if isinstance(v, (int, float)) or str(v).isdigit():
        return int(v) / 1000
    try:
        return datetime.fromisoformat(str(v).replace("Z", "+00:00")).timestamp()
    except ValueError:
        return 0


def calls():
    out = []
    for p in (ctx.SIDEKICK / "calls").glob("*"):
        nb = p / "notebook.jsonl"
        if not nb.exists():
            continue
        title, cards = "", 0
        for l in nb.read_text(errors="replace").splitlines():
            try:
                e = json.loads(l)
            except ValueError:
                continue
            if e.get("type") == "call":
                title = e.get("title", "")
            cards += e.get("type") == "note"
        if cards:
            out.append({"id": p.name, "title": title, "cards": cards, "at": nb.stat().st_mtime})
    return sorted(out, key=lambda c: -c["at"])


def tool_summary(b):
    name, inp = b.get("name", "?"), b.get("input") or {}
    if name == "Bash":
        c = re.sub(r"^\s*(export SIDEKICK_HOME=\S+;\s*|cd \S+;\s*)+", "", inp.get("command", ""))
        c = re.sub(r"\S*/(?:bin|scripts)/(sidekick[\w-]*)", r"\1", c)
        return "$ " + c
    if name == "ToolSearch":
        return ""
    return f"{name.removeprefix('mcp__').replace('tuple-portal__', '')} {json.dumps(inp, ensure_ascii=False)}"


def note_commands(cmd):
    out = []
    for line in re.split(r"\n|;|&&", cmd):
        try:
            words = shlex.split(line)
        except ValueError:
            words = line.split()
        for i, w in enumerate(words):
            if w in ("note", "options") and i >= 2 and words[i - 2] == "--call":
                rest = words[i + 1:]
                nid = rest[rest.index("--id") + 1] if "--id" in rest and rest.index("--id") + 1 < len(rest) else None
                title = next((r for r in rest if not r.startswith("-") and not UUID.fullmatch(r) and r != nid), "")
                out.append((w, nid, title))
                break
    return out


def reasons(call):
    folder = ctx.SIDEKICK / "calls" / call
    sessions = ctx.read_json(folder / "agent.json").get("sessions") or []
    out = {}
    for s in sessions:
        path = Path(s.get("transcript") or "")
        if not path.exists():
            continue
        turn = {"heard": [], "thinking": [], "tools": [], "decision": "", "model": s.get("model", "")}
        pending = {}
        wrote = []
        for raw in path.read_text(errors="replace").splitlines():
            try:
                d = json.loads(raw)
            except ValueError:
                continue
            kind, msg = d.get("type"), d.get("message") or {}
            content = msg.get("content")
            if kind == "user" and isinstance(content, str) and "<task-notification>" in content:
                for ev in EVENT.findall(content):
                    for line in ev.splitlines():
                        m = SPEECH.match(line.strip())
                        if m:
                            turn["heard"].append(f"{m.group(2).split()[0]}: {m.group(3).strip()}")
                        elif line.startswith("[sidekick] reaction") or line.startswith("[sidekick] ask"):
                            turn["heard"].append(line.strip())
            elif kind == "assistant" and isinstance(content, list):
                for b in content:
                    t = b.get("type")
                    if t == "thinking" and b.get("thinking", "").strip():
                        turn["thinking"].append(b["thinking"].strip())
                    elif t == "text" and b.get("text", "").strip():
                        turn["decision"] = b["text"].strip()
                    elif t == "tool_use":
                        cmd = (b.get("input") or {}).get("command", "")
                        nc = note_commands(cmd) if b.get("name") == "Bash" else []
                        if nc:
                            pending[b["id"]] = nc
                        else:
                            summary = tool_summary(b)
                            if summary:
                                turn["tools"].append(summary[:400])
            elif kind == "user" and isinstance(content, list):
                for b in content:
                    if b.get("type") == "tool_result" and b.get("tool_use_id") in pending:
                        cmds = pending.pop(b["tool_use_id"])
                        text = b.get("content")
                        text = text if isinstance(text, str) else json.dumps(text)
                        if b.get("is_error") and not UUID.search(text):
                            turn["tools"].append(f"✗ refused: {text[:200]}")
                            continue
                        printed = UUID.findall(text)
                        for verb, nid, title in cmds:
                            if nid:
                                wrote.append((nid, "revised"))
                                if nid in printed:
                                    printed.remove(nid)
                            elif printed:
                                wrote.append((printed.pop(0), "wrote"))
            elif kind == "system" and d.get("subtype") == "turn_duration":
                if wrote:
                    for nid, how in wrote:
                        out.setdefault(nid, []).append({**turn, "how": how, "seconds": round(d.get("durationMs", 0) / 1000, 1),
                                                        "heard": turn["heard"][-12:]})
                turn = {"heard": [], "thinking": [], "tools": [], "decision": "", "model": s.get("model", "")}
                wrote = []
    return out


def call_data(call):
    folder = ctx.SIDEKICK / "calls" / call
    events = []
    for l in (ctx.read(folder / "notebook.jsonl") or "").splitlines():
        try:
            events.append(json.loads(l))
        except ValueError:
            pass
    said = set()
    for raw in (ctx.read(folder / "feed.log") or "").splitlines():
        m = SPEECH.match(raw.split("\t", 1)[-1])
        if m:
            said.add((stamp(m.group(1)), m.group(2), m.group(3).strip()))
    speech = [{"t": t, "who": who, "text": text} for t, who, text in sorted(said)]
    start = speech[0]["t"] if speech else (stamp(events[0]["at"]) if events else 0)
    why = reasons(call)
    cards, topic, title = {}, "", ""
    for e in events:
        k = e.get("type")
        if k == "call":
            title = e.get("title", title)
        elif k == "topic":
            topic = e.get("title", "")
        elif k == "note":
            body = e.get("body") or ""
            if e.get("options"):
                body = "\n".join(f"- **{o.get('name')}**: " + "; ".join(["+ " + p for p in o.get("pros") or []] + ["− " + c for c in o.get("cons") or []])
                                 for o in e["options"])
            cards[e["id"]] = {"id": e["id"], "t": stamp(e["at"]), "title": e.get("title", ""), "body": body, "topic": topic,
                              "running": bool(e.get("running")), "pinned": bool(e.get("pinned")), "links": e.get("links") or [],
                              "actions": [a.get("label") for a in e.get("actions") or []], "revisions": 0, "live": [],
                              "why": why.get(e["id"], [])}
        elif k == "revise" and e.get("note") in cards:
            c = cards[e["note"]]
            c["revisions"] += 1
            c["title"] = e.get("title") or c["title"]
            c["body"] = e.get("body", c["body"])
        elif k == "vote" and e.get("note") in cards:
            c = cards[e["note"]]
            mark = ("👍" if e.get("vote") == "up" else "👎") + (f" {e['reason']}" if e.get("reason") else "")
            c["live"] = [x for x in c["live"] if not mark.startswith(x)] + [mark]
        elif k in ("share", "delete") and e.get("note") in cards:
            cards[e["note"]]["live"].append("shared" if k == "share" else "deleted")
        elif k == "action" and e.get("note") in cards and e.get("state") in ("running", "done"):
            cards[e["note"]]["live"].append("used its action")
    evals = {}
    for l in (ctx.read(folder / "eval.jsonl") or "").splitlines():
        try:
            r = json.loads(l)
            evals[r["note"]] = r
        except (ValueError, KeyError):
            pass
    return {"id": call, "title": title, "start": start, "speech": speech, "cards": sorted(cards.values(), key=lambda c: c["t"]),
            "evals": evals}


def learn(call):
    import subprocess
    folder = ctx.SIDEKICK / "calls" / call
    if not (folder / "eval.jsonl").exists():
        return {"started": False, "why": "no ratings yet"}
    prompt = (f"The operator just rated the cards Sidekick wrote on call {call} in the card evaluator: "
              f"{folder / 'eval.jsonl'} (the last line per note wins; rating up, meh or down, with reasons and a comment). "
              "Fold them into me.md the way the wiki skill's \"After a call\" step 6 says: patterns they valued under \"What "
              "lands with me\", how Sidekick should behave under \"Standing constraints\". Read me.md and the call page's "
              f"Agent contributions first; change nothing else. Commit. SIDEKICK_HOME is {ctx.SIDEKICK}. Ask no questions.")
    model = ctx.agent_model()
    cmd = ["claude", "-p", "--model", model, *ctx.claude_plugin_args(), "--permission-mode", "auto", "--max-turns", "20",
           "--append-system-prompt", prompt, f"{ctx.plugin_skill('wiki')} learn from ratings on {call}"]
    log = open(folder / "learn.log", "a")
    subprocess.Popen(cmd, cwd=str(ctx.project()), stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
                     env={**os.environ, "SIDEKICK_HOME": str(ctx.SIDEKICK)}, start_new_session=True)
    return {"started": True}


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def send(self, body, kind="application/json", code=200):
        data = body if isinstance(body, bytes) else (body if isinstance(body, str) else json.dumps(body)).encode()
        self.send_response(code)
        self.send_header("Content-Type", kind + "; charset=utf-8")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def call_ok(self, call):
        return bool(re.fullmatch(r"[\w-]+", call or "")) and (ctx.SIDEKICK / "calls" / call).is_dir()

    def do_GET(self):
        if self.path == "/":
            return self.send(PAGE.replace("__DEFAULT__", json.dumps(self.server.default)), "text/html")
        if self.path == "/api/calls":
            return self.send(calls())
        m = re.fullmatch(r"/api/call/([\w-]+)", self.path)
        if m and self.call_ok(m.group(1)):
            return self.send(call_data(m.group(1)))
        self.send({"error": "not found"}, code=404)

    def do_POST(self):
        if self.path == "/api/learn":
            r = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
            if not self.call_ok(r.get("call")):
                return self.send({"error": "bad call"}, code=400)
            return self.send(learn(r["call"]))
        if self.path != "/api/eval":
            return self.send({"error": "not found"}, code=404)
        r = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
        if not self.call_ok(r.get("call")) or not UUID.fullmatch(str(r.get("note", ""))):
            return self.send({"error": "bad call or note"}, code=400)
        rec = {"at": int(time.time() * 1000), "note": r["note"], "rating": r.get("rating"),
               "reasons": [str(x)[:40] for x in r.get("reasons") or []][:8], "comment": str(r.get("comment", ""))[:2000],
               "title": str(r.get("title", ""))[:200]}
        with open(ctx.SIDEKICK / "calls" / r["call"] / "eval.jsonl", "a") as f:
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")
        self.send(rec)


PAGE = r"""<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Card Evaluator</title>
<style>
:root{--bg:#f6f5f0;--panel:#fffefa;--ink:#22211d;--faint:#77736a;--rule:#e2dfd5;--accent:#2f6fde;--up:#1f8a4c;--down:#c2412d;--meh:#9a7b12;--hi:#fff3c4}
@media (prefers-color-scheme:dark){:root{--bg:#1b1b19;--panel:#242421;--ink:#ecebe6;--faint:#9b978d;--rule:#3a3934;--accent:#7aa7ff;--up:#4cc27f;--down:#ff7a63;--meh:#e1bf4a;--hi:#4a4220}}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;height:100vh;display:flex;flex-direction:column}
header{display:flex;gap:12px;align-items:center;padding:10px 16px;border-bottom:1px solid var(--rule);background:var(--panel)}
header h1{font-size:15px;margin:0;font-weight:600}#learn{font:inherit;border:1px solid var(--accent);background:var(--accent);color:#fff;border-radius:6px;padding:5px 12px;cursor:pointer}#learn:disabled{opacity:.5;cursor:default}select{font:inherit;padding:4px 6px;max-width:420px}
.progress{margin-left:auto;color:var(--faint)}
main{flex:1;display:grid;grid-template-columns:300px 1fr 1.1fr;min-height:0}
.col{overflow:auto;border-right:1px solid var(--rule)}
.list .item{padding:8px 12px;border-bottom:1px solid var(--rule);cursor:pointer;display:flex;gap:8px}
.list .item:hover{background:var(--hi)}.list .item.on{background:var(--hi);box-shadow:inset 3px 0 var(--accent)}
.list .time{color:var(--faint);font-variant-numeric:tabular-nums;min-width:38px}.list .ttl{flex:1}
.list .mark{min-width:18px;text-align:right}
.transcript{padding:12px 16px}.line{padding:2px 0;color:var(--faint)}.line b{color:var(--ink);font-weight:600}
.line.near{color:var(--ink)}.line .ts{font-variant-numeric:tabular-nums;font-size:12px;margin-right:6px;color:var(--faint)}
.cardmark{margin:8px 0;padding:6px 10px;border-left:3px solid var(--accent);background:var(--panel);font-weight:600}
.detail{padding:16px 20px;border-right:0}
.card{background:var(--panel);border:1px solid var(--rule);border-radius:8px;padding:12px 14px}
.card h2{font-size:16px;margin:0 0 6px}.card .body{white-space:pre-wrap}.meta{color:var(--faint);font-size:12px;margin-top:6px}
h3{font-size:13px;margin:18px 0 6px;color:var(--faint);font-weight:600}
.why pre{white-space:pre-wrap;font:12px/1.4 ui-monospace,Menlo,monospace;background:var(--panel);border:1px solid var(--rule);border-radius:6px;padding:8px;margin:4px 0;max-height:260px;overflow:auto}
.decision{font-weight:600}
.rate{display:flex;gap:8px;margin-top:10px}.rate button,.chips button{font:inherit;border:1px solid var(--rule);background:var(--panel);color:var(--ink);border-radius:6px;padding:6px 12px;cursor:pointer}
.rate button.on[data-r=up]{background:var(--up);color:#fff;border-color:var(--up)}.rate button.on[data-r=down]{background:var(--down);color:#fff;border-color:var(--down)}
.rate button.on[data-r=meh]{background:var(--meh);color:#fff;border-color:var(--meh)}
.chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.chips button{padding:3px 9px;font-size:13px}.chips button.on{background:var(--accent);color:#fff;border-color:var(--accent)}
textarea{width:100%;min-height:60px;margin-top:10px;font:inherit;padding:8px;border:1px solid var(--rule);border-radius:6px;background:var(--panel);color:var(--ink)}
.saved{color:var(--faint);font-size:12px;margin-top:4px;min-height:16px}.keys{color:var(--faint);font-size:12px;margin-top:14px}
@media (max-width:900px){main{grid-template-columns:1fr}.col{border-right:0;border-bottom:1px solid var(--rule);max-height:50vh}}
</style></head><body>
<header><h1>Card Evaluator</h1><select id="call"></select><span class="progress" id="progress"></span><button id="learn" title="Fold these ratings into what Sidekick knows you value (me.md)">Teach Sidekick</button></header>
<main><div class="col list" id="list"></div><div class="col transcript" id="transcript"></div><div class="col detail" id="detail"></div></main>
<script>
const REASONS={up:["new fact","great find","right moment","useful action"],down:["restates the call","already known","wrong","guess","not relevant","too long","too late","duplicate"],meh:["interesting, not now","too long","too late","partly right"]};
let D=null,cur=0,state={};
const $=s=>document.querySelector(s),esc=s=>String(s??"").replace(/[&<>"]/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c]));
const md=s=>esc(s).replace(/\*\*(.+?)\*\*/g,"<b>$1</b>");
const clock=t=>{const s=Math.max(0,Math.round(t-D.start));return Math.floor(s/60)+":"+String(s%60).padStart(2,"0")};
async function loadCalls(){const cs=await (await fetch("/api/calls")).json();const def=__DEFAULT__;
 $("#call").innerHTML=cs.map(c=>`<option value="${c.id}">${esc(c.title||c.id.slice(0,8))} · ${new Date(c.at*1000).toLocaleString([], {month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})} · ${c.cards} cards</option>`).join("");
 if(def&&cs.some(c=>c.id===def))$("#call").value=def;load($("#call").value)}
async function load(id){D=await (await fetch("/api/call/"+id)).json();state={};for(const [k,v] of Object.entries(D.evals))state[k]=v;cur=D.cards.findIndex(c=>!state[c.id]);if(cur<0)cur=0;render()}
function mark(c){const e=state[c.id];if(e)return {up:"👍",down:"👎",meh:"〰"}[e.rating]||"";return c.live.length?"·":""}
function render(){const done=D.cards.filter(c=>state[c.id]).length;$("#progress").textContent=`${done} of ${D.cards.length} rated`;
 $("#list").innerHTML=D.cards.map((c,i)=>`<div class="item ${i===cur?"on":""}" data-i="${i}"><span class="time">${clock(c.t)}</span><span class="ttl">${esc(c.title)}</span><span class="mark">${mark(c)}</span></div>`).join("");
 document.querySelectorAll(".list .item").forEach(el=>el.onclick=()=>{cur=+el.dataset.i;render()});
 const on=$(".list .item.on");on&&on.scrollIntoView({block:"nearest"});
 const c=D.cards[cur];if(!c){$("#detail").innerHTML="No cards on this call.";return}
 const lines=D.speech.filter(s=>s.t>=c.t-240&&s.t<=c.t+60);
 let html="",placed=false;for(const s of lines){if(!placed&&s.t>c.t){html+=`<div class="cardmark" id="here">▶ ${esc(c.title)}</div>`;placed=true}
  html+=`<div class="line ${s.t>=c.t-90&&s.t<=c.t?"near":""}"><span class="ts">${clock(s.t)}</span><b>${esc(s.who.split(" ")[0])}</b> ${esc(s.text)}</div>`}
 if(!placed)html+=`<div class="cardmark" id="here">▶ ${esc(c.title)}</div>`;
 $("#transcript").innerHTML=html||"<p>No speech logged around this card.</p>";const here=$("#here");here&&here.scrollIntoView({block:"center"});
 const e=state[c.id]||{};const w=c.why;
 const why=w.length?w.map(t=>`<div class="why"><div class="decision">${t.how==="revised"?"Revised":"Wrote"} · ${esc(t.model)} · ${t.seconds}s — ${esc(t.decision)}</div>
  ${t.thinking.length?`<pre>${esc(t.thinking.join("\n\n"))}</pre>`:""}${t.tools.length?`<pre>${esc(t.tools.join("\n"))}</pre>`:""}</div>`).join(""):"<p class='meta'>No agent transcript found for this card (an ask session or an older call).</p>";
 $("#detail").innerHTML=`<div class="card"><h2>${esc(c.title)}</h2><div class="body">${md(c.body)}</div>
  <div class="meta">${clock(c.t)}${c.topic?" · "+esc(c.topic):""}${c.running?" · running":""}${c.pinned?" · pinned":""}${c.revisions?" · revised "+c.revisions+"×":""}${c.actions.length?" · action: "+esc(c.actions.join(", ")):""}${c.live.length?" · live: "+esc(c.live.join(", ")):""}</div></div>
  <div class="rate">${["up","meh","down"].map(r=>`<button data-r="${r}" class="${e.rating===r?"on":""}">${{up:"👍 Useful",meh:"〰 Meh",down:"👎 Not useful"}[r]}</button>`).join("")}</div>
  <div class="chips" id="chips"></div><textarea id="comment" placeholder="What would have been better? (optional)">${esc(e.comment||"")}</textarea><div class="saved" id="saved"></div>
  <h3>Why the agent wrote it</h3>${why}<div class="keys">1 useful · 2 meh · 3 not useful · j/k next/previous · Enter saves the comment</div>`;
 document.querySelectorAll(".rate button").forEach(b=>b.onclick=()=>rate(b.dataset.r));chips();
 $("#comment").addEventListener("keydown",ev=>{if(ev.key==="Enter"&&!ev.shiftKey){ev.preventDefault();save()}});
 $("#comment").addEventListener("blur",()=>{if(state[c.id]&&$("#comment").value!==(state[c.id].comment||""))save()})}
function chips(){const c=D.cards[cur],e=state[c.id]||{};const r=e.rating;$("#chips").innerHTML=r?REASONS[r].map(x=>`<button class="${(e.reasons||[]).includes(x)?"on":""}">${esc(x)}</button>`).join(""):"";
 document.querySelectorAll("#chips button").forEach(b=>b.onclick=()=>{const rs=new Set(state[c.id].reasons||[]);rs.has(b.textContent)?rs.delete(b.textContent):rs.add(b.textContent);state[c.id].reasons=[...rs];save();chips()})}
function rate(r){const c=D.cards[cur];const prev=state[c.id]||{};state[c.id]={...prev,rating:r,reasons:prev.rating===r?prev.reasons||[]:[]};save();render()}
async function save(){const c=D.cards[cur],e=state[c.id];if(!e)return;e.comment=$("#comment")?$("#comment").value:e.comment||"";
 await fetch("/api/eval",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({call:D.id,note:c.id,title:c.title,rating:e.rating,reasons:e.reasons||[],comment:e.comment})});
 const s=$("#saved");if(s)s.textContent="Saved"}
document.addEventListener("keydown",ev=>{if(ev.target.tagName==="TEXTAREA"||ev.target.tagName==="SELECT")return;
 if(ev.key==="j"&&cur<D.cards.length-1){cur++;render()}else if(ev.key==="k"&&cur>0){cur--;render()}
 else if(ev.key==="1")rate("up");else if(ev.key==="2")rate("meh");else if(ev.key==="3")rate("down")});
$("#learn").onclick=async()=>{const b=$("#learn");b.disabled=true;const r=await (await fetch("/api/learn",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({call:D.id})})).json();
 b.textContent=r.started?"Learning… (updates me.md in a minute)":"Rate some cards first";setTimeout(()=>{b.disabled=false;b.textContent="Teach Sidekick"},8000)};
$("#call").onchange=()=>load($("#call").value);loadCalls();
</script></body></html>"""


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--call")
    ap.add_argument("--port", type=int, default=8765)
    ap.add_argument("--no-open", action="store_true")
    ap.add_argument("--env", choices=ctx.CLIS, help=argparse.SUPPRESS)
    a = ap.parse_args()
    default = None
    if a.call:
        hits = [p.name for p in (ctx.SIDEKICK / "calls").glob(f"{a.call}*") if p.is_dir()]
        default = hits[0] if len(hits) == 1 else None
    server = ThreadingHTTPServer(("127.0.0.1", a.port), Handler)
    server.default = default
    url = f"http://127.0.0.1:{a.port}/"
    print(f"Card Evaluator: {url}  (ratings → {ctx.SIDEKICK}/calls/<call>/eval.jsonl; Ctrl-C to stop)")
    if not a.no_open:
        webbrowser.open(url)
    server.serve_forever()


if __name__ == "__main__":
    main()
